﻿using System.Collections.Generic;
using System.IO;
using IronPython.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
//using SPCoder.Context;

namespace SPCoder.Scripting
{
    /// <summary>
    /// 
    /// </summary>
    /// <author>Damjan Tomic</author>
    public class IronPythonEngine
    {
        private ScriptEngine m_engine = Python.CreateEngine();
        private ScriptScope m_scope = null;
        private ScriptSource source;
        //private IronPythonContext myContext = new IronPythonContext();
        MemoryStream sout = new MemoryStream();

        public ScriptScope Scope
        {
            get { return m_scope; }
        }

        public IronPythonEngine()
        {
            m_scope = m_engine.CreateScope();            
            //myContext.Scope = m_scope;             
        }

        public void SetVariables(IDictionary<string, object> variables)
        {
            foreach (KeyValuePair<string, object> pair in variables)
            {
                m_scope.SetVariable(pair.Key, pair.Value);
            }
        }
        
        public void SetVariable(string name, object value)
        {            
            m_scope.SetVariable(name, value);
        }

        public object Execute(string sourceCode)
        {
            try
            {
                source = m_engine.CreateScriptSourceFromString(sourceCode, SourceCodeKind.Statements);
                object result = source.Execute(m_scope);
                return result;
            }
            catch (System.Exception exc)
            {
                throw exc;
            }
        }

//        public object GetObjectFromScript(string sourceCode)
//        {
//            object result = null;
//            m_scope.SetVariable("__temporaryObject", result);
//            string sourceCode = ""
//
//        }
    }
}